package com.umfwechat.h5.controller.business;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.util.logging.resources.logging;

import com.umfwechat.common.code.RetCode;
import com.umfwechat.common.constant.CommonConsts;
import com.umfwechat.common.constant.MsgConsts;
import com.umfwechat.common.constant.ValueConsts;
import com.umfwechat.util.DesIDUtil;
import com.umfwechat.util.ReqMessageUtil;
import com.umfwechat.util.ResultJsonUtil;
import com.umfwechat.util.SmsCheckUtil;
import com.umfwechat.util.StringUtil;
import com.umfwechat.wx.service.WeixinService;
import com.umpay.sp.model.common.ReqMessage;
import com.umpay.sp.model.common.ResMessage;
import com.umpay.sp.model.saas.StoreInf;
import com.umpay.sp.service.saas.remote.StoreInfServiceRemote;
import com.umpay.sp.service.sys.remote.UserServiceRemote;

/**
 * @desc  商户登录
 * @author 
 * @date 2017-11-10 下午2:40:29
 */
@Controller
@RequestMapping("/h5/registerController")
public class RegisterController {

	private static Logger logger = LoggerFactory.getLogger(RegisterController.class);
	
	// 查询第三方用户、用户详情接口
	@Resource
	private UserServiceRemote userServiceRemote_sp;

	// 查询店铺部署详情列表接口
	@Resource
	private StoreInfServiceRemote storeInfServiceRemote;
	
	@Autowired
	private WeixinService weixinService;
	/**
	 * 下发验证码短信接口
	 * @param request
	 * @param reponse
	 * @param bankMobileId
	 * @return
	 */
	@RequestMapping(value = "/send",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String send(HttpServletRequest request, HttpServletResponse reponse,String bankMobileId) {
		HttpSession session = request.getSession();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		if (StringUtil.isEmpty(bankMobileId)) { // 校验手机号是否为空
			logger.info("获取手机号失败!");
			return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433061);
		}
		try {
			// ~~~~~~~~~~~~~~~~~~~~~~~~~调用下发短信息验证码接口~~~~~~~~~~~~~~~~~~~~~~~~~
			String productId = ValueConsts.PRODUCTID;
			logger.info("【下发短信验证码接口】入参" + CommonConsts.BANKMOBILEID + "：" + bankMobileId + CommonConsts.PRODUCTID+"：" + productId);
			Map<String, String> res = SmsCheckUtil.send(bankMobileId, productId);
			logger.info("【下发短信验证码接口】出参：" + res);
			if (res == null) { // 调用失败
				logger.info("下发短信验证码失败!");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
			}
			if (!RetCode.SUCCESS.equals(res.get(CommonConsts.RETCODE))) { // 失败
				logger.info("下发短信验证码错误!");
				return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
			}
			session.setAttribute(CommonConsts.SMSVERIFYTRACE,StringUtil.trim(res.get(CommonConsts.SMSVERIFYTRACE)));
			resultMap.put(CommonConsts.BANKMOBILEID, bankMobileId); // 手机号
			resultMap.put(CommonConsts.VERIFYCODE, StringUtil.trim(res.get(CommonConsts.VERIFYCODE)));
			logger.info("下发短信验证码成功！");
			return ResultJsonUtil.resultJson(RetCode.SUCCESS, MsgConsts.I00433063 ,resultMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("下发短信验证码失败!",e);
		}
		return ResultJsonUtil.resultJson(RetCode.FAIL, MsgConsts.E00433062);
	}
	
	/**
	 * 登录
	 * @param request
	 * @param reponse
	 * @param bankMobileId手机号
	 * @param verifyCode验证码
	 * @param payeeInidcard身份证号
	 * @return
	 */
	@RequestMapping(value = "/register",produces="application/json;charset=UTF-8")
	@ResponseBody
	public String register(HttpServletRequest request, HttpServletResponse reponse,String bankMobileId,String verifyCode,String payeeInidcard) {
		
		HttpSession session=request.getSession();
	
		String openId=StringUtil.trim(session.getAttribute(CommonConsts.OPENID));	
		//openId="o9Gdj1Z89rbDTqeWZN5NCCbPR00c";
		if(StringUtil.isEmpty(openId)){
			logger.info("【从session中获取openid失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433001);
		}

		logger.info("【调用校验验证码信息接口，校验短信验证码】====开始！====+++++++");
		if(StringUtil.isEmpty(bankMobileId)){
			logger.info("【获取手机号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433061);
		}
		if(StringUtil.isEmpty(verifyCode)){
			logger.info("【获取验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433064);
		}
		String smsVerifyTrace=StringUtil.trim(session.getAttribute(CommonConsts.SMSVERIFYTRACE));	//从session中获取流水号
		if(StringUtil.isEmpty(smsVerifyTrace)){
			logger.info("【获取流水号失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433062);
		}
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~检验短信验证码接口~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		Map<String,String> map=SmsCheckUtil.checksms(bankMobileId, smsVerifyTrace, verifyCode);
		if(map.isEmpty()||map==null){
			logger.info("【校验验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433078);
		}
		if(!RetCode.SUCCESS.equals(map.get(CommonConsts.RETCODE))){		//验证码错误
			logger.info("【校验验证码失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433078);
		}
		logger.info("【调用校验验证码信息接口，校验短信验证码】======结束！====+++++++");
		
		/*
		 * 通过身份证号查询店铺列表
		 */
		ReqMessage req = ReqMessageUtil.makeSpReq();
		ResMessage res = new ResMessage();
		req.put(CommonConsts.PAYEEINIDCARD, DesIDUtil.encID(StringUtil.trim(payeeInidcard)));
		try {
			logger.info("【根据身份证号查询店铺列表】请求参数：" + req);
			res = storeInfServiceRemote.getStoreInfList(req);
			logger.info("【根据身份证号查询店铺列表】返回参数：" + res);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【根据身份证号查询店铺列表】异常",e);
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433003);
		}
		if(!RetCode.SUCCESS.equals(res.getRetCode())){
			logger.info("【根据身份证号查询店铺列表】失败");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433003);
		}else if(ValueConsts.FLAG_ZERO.equals(StringUtil.trim(res.getValue(CommonConsts.TOTAL_SIZE)))){
			logger.info("店铺部署详情列表获取数据为空 ");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433123);
		}
		
		//获取店铺列表
		@SuppressWarnings("unchecked")
		List<StoreInf> list = (List<StoreInf>)res.getValue(CommonConsts.STOREINF_LIST);
		
		StoreInf inf = list.get(0);
		String payeeMobileId = inf.getPayeeMobileId();//获取店铺手机号
		String merId = inf.getMerId();//获取店铺主商户
		logger.info(merId+"主商户merId");
		if(!bankMobileId.equals(payeeMobileId)){
			logger.info(merId+"主商户身份证存在，手机号不对 ");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433124);
		}
		if(StringUtil.isEmpty(merId)){
			merId=inf.getStoreId();
			logger.info(merId+"主商户storeId");
		}
		String groupId=ValueConsts.ONE_ZERO_THREE;//个体标签
		for (StoreInf storeInf : list) {
			String storeType = storeInf.getStoreType();//店铺类型
			if(ValueConsts.STATE_ZERO.equals(storeType)){
				logger.info(merId+"主商户店铺列表中有小微商户");
				groupId=ValueConsts.ONE_ZERO_ONE;//小微标签
				break;
			}
		}
		
		//用户列表查询(主商户下的收款人)
		ReqMessage reqMe = ReqMessageUtil.makeSpReq();
		reqMe.getReqMap().put(CommonConsts.MER_FLAG, merId);//主商户
		reqMe.getReqMap().put(CommonConsts.STATE,ValueConsts.USER_NOMAL);//状态
		reqMe.getReqMap().put(CommonConsts.RANK,ValueConsts.PAYEE);//角色
		reqMe.put(CommonConsts.CURRENT_PAGE, String.valueOf(1));
		reqMe.put(CommonConsts.PAGE_SIZE, String.valueOf(100));
		ResMessage resMe=new ResMessage();
		try {
			logger.info("【用户列表查询接口】输入参数：ReqMessage="+reqMe);
		    resMe = userServiceRemote_sp.queryList(reqMe);
			logger.info("【用户列表查询接口】输出参数：ResMessage==" + resMe);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【用户列表查询接口】异常",e);
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433003);
		}
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> resultList = (List<Map<String, Object>>)resMe.getValue(CommonConsts.RESULT_LIST);
		//查询出的用户数量
		Integer totalSize =(Integer) resMe.getValue(CommonConsts.TOTAL_SIZE);
		
		if(totalSize <= 0){
			logger.info("用户列表查询数据为空 ");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433001);
		}
		Map<String, Object> objMap = resultList.get(0);
		String userId =StringUtil.trim(objMap.get(CommonConsts.USERID));//用户Id
		
		//根据userId查询此身份证号的主商户是否被人绑定
		ReqMessage reqM = ReqMessageUtil.makeSpReq();
		reqM.getReqMap().put(CommonConsts.USERID, userId);
		reqM.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_NOMAL);
		ResMessage resM=new ResMessage();
		try {
			logger.info("【A查询第三方网站用户接口】输入参数 ：ReqMessage=" + reqM);
		    resM = userServiceRemote_sp.queryUserBind(reqM);
			logger.info("【A查询第三方网站用户接口】输出参数 ：ResMessage=" + resM);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【A查询第三方网站用户接口】异常",e);
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		//第三方网站查询失败
		if(!RetCode.SUCCESS.equals(resM.getRetCode())&&!RetCode.NO_DATA.equals(resM.getRetCode())){
			logger.info("【A查询第三方网站用户接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		
		if(RetCode.SUCCESS.equals(resM.getRetCode())){
			
			String externalUserId = StringUtil.trim(resM.getValue(CommonConsts.EXTERNAL_USER_ID));//获取与此店铺绑定的外部用户Id
			if(openId.equals(externalUserId)){//判断查出外部用户Id是否是与操作者用户Id相等
				Map<String, Object> result = weixinService.getUserGroup(openId);//获取对应的公众号菜单标签
				logger.info("此微信openId="+openId+"的原标签是="+result);
				if(RetCode.SUCCESS.equals(result.get(CommonConsts.RETCODE))){
					if(StringUtil.isNotEmpty(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
						if(!groupId.equals(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
							Integer valueOf = Integer.valueOf(groupId);
							boolean group = weixinService.addUserGroup(openId,valueOf);//重新标记公众号菜单标签
							logger.info("此微信openId="+openId+"重新打"+groupId+"标签flag="+group);
						}
					}
				}else{
					Integer valueOf = Integer.valueOf(groupId);
					boolean group = weixinService.addUserGroup(openId,valueOf);
					logger.info("此微信openId="+openId+"重新打"+groupId+"标签flag="+group);
				}
				return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE);
			}else{
				//解绑老用户
				ReqMessage reqMes = ReqMessageUtil.makeSpReq();
				reqMes.getReqMap().put(CommonConsts.EXTERNALUSERID,externalUserId);
				reqMes.getReqMap().put(CommonConsts.USERID,userId);
				reqMes.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_LOG_OFF);
				ResMessage resMes=new ResMessage();
				try {
					logger.info("【A解绑第三方网站用户接口】输入参数 ：=" + reqMes);
					resMes = userServiceRemote_sp.unBindUser(reqMes);
					logger.info("【A解绑第三方网站用户接口】输出参数：=" +resMes);
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("【A解绑第三方网站用户接口】异常",e);
					return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
				}
				if(!RetCode.SUCCESS.equals(resMes.getRetCode())){
					logger.info("【A解绑第三方网站用户接口失败】 ");
					return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433125);
				}else{
					boolean group = weixinService.addUserGroup(externalUserId,0);
					logger.info("此微信openId="+openId+"打成无角色标签="+group);
				}
				
			}
			
		}
		
		//根据openId查询操作者是否已经绑定过
		ReqMessage reqMess = ReqMessageUtil.makeSpReq();
		reqMess.getReqMap().put(CommonConsts.EXTERNALUSERID, openId);
		reqMess.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_NOMAL);
		ResMessage resMess=new ResMessage();
		try {
			logger.info("【B查询第三方网站用户接口】输入参数 ：ReqMessage=" + reqMess);
		    resMess = userServiceRemote_sp.queryUserBind(reqMess);
			logger.info("【B查询第三方网站用户接口】输出参数 ：ResMessage=" + resMess);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【B查询第三方网站用户接口】异常",e);
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		
		//第三方网站查询失败
		if(!RetCode.SUCCESS.equals(resMess.getRetCode())&&!RetCode.NO_DATA.equals(resMess.getRetCode())){
			logger.info("【B查询第三方网站用户接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		if(RetCode.SUCCESS.equals(resMess.getRetCode())){
			//把老店铺解绑
			String userIdTwo = StringUtil.trim(resMess.getValue(CommonConsts.USERID));
			
			ReqMessage reqMessa = ReqMessageUtil.makeSpReq();
			reqMessa.getReqMap().put(CommonConsts.EXTERNALUSERID,openId);
			reqMessa.getReqMap().put(CommonConsts.USERID,userIdTwo);
			reqMessa.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_LOG_OFF);
			ResMessage resMessa=new ResMessage();
			try {
				logger.info("【B解绑第三方网站用户接口】输入参数：" + reqMessa);
				resMessa = userServiceRemote_sp.unBindUser(reqMessa);
				logger.info("【B解绑第三方网站用户接口】输出参数：" +resMessa);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("【B解绑第三方网站用户接口】异常",e);
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
			}
			
			if(!RetCode.SUCCESS.equals(resMessa.getRetCode())){
				logger.info("【B解绑第三方网站用户接口失败 】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433125);
			}
			
		}
        
		ReqMessage reqMessag = ReqMessageUtil.makeSpReq();
		reqMessag.getReqMap().put(CommonConsts.EXTERNALUSERID, openId);
		reqMessag.getReqMap().put(CommonConsts.USERID,userId);
		reqMessag.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_LOG_OFF);
		ResMessage resMessag=new ResMessage();
		try {
			logger.info("【C查询第三方网站用户接口】输入参数 :" + reqMessag);
		    resMessag = userServiceRemote_sp.queryUserBind(reqMessag);
			logger.info("【C查询第三方网站用户接口】输出参数 :" + resMessag);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("【C查询第三方网站用户接口】异常",e);
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}
		
		//第三方网站查询失败
		if(!RetCode.SUCCESS.equals(resMessag.getRetCode())&&!RetCode.NO_DATA.equals(resMessag.getRetCode())){
			logger.info("【C查询第三方网站用户接口失败】");
			return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
		}

		if(RetCode.SUCCESS.equals(resMessag.getRetCode())){
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			reqMessage.getReqMap().put(CommonConsts.EXTERNALUSERID,openId);
			reqMessage.getReqMap().put(CommonConsts.USERID,userId);
			reqMessage.getReqMap().put(CommonConsts.STATE,ValueConsts.EXTERNAL_USER_NOMAL);
			ResMessage resMessage=new ResMessage();
			try {
				logger.info("【绑定第三方网站用户接口unBindUser】输入参数：" + reqMessage);
				resMessage = userServiceRemote_sp.unBindUser(reqMessage);
				logger.info("【绑定第三方网站用户接口unBindUser】输出参数：" +resMessage);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("【绑定第三方网站用户接口unBindUser】异常",e);
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
			}
			if(!RetCode.SUCCESS.equals(resMessage.getRetCode())){
				logger.info("【绑定第三方网站用户接口失败unBindUser 】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433125);
			}
		}else if(RetCode.NO_DATA.equals(resMessag.getRetCode())){
			ReqMessage reqMessage = ReqMessageUtil.makeSpReq();
			reqMessage.getReqMap().put(CommonConsts.EXTERNALUSERID,openId);//外部用户Id
			reqMessage.getReqMap().put(CommonConsts.USERID,userId);//用户Id
			reqMessage.getReqMap().put(CommonConsts.EXTERNAL_WEB,ValueConsts.EXTERNAL_USER_GENRE);//外部网站标识
			ResMessage resMessage =new ResMessage();
			try {
				logger.info("【绑定第三方网站用户接口bindUser】输入参数：" + reqMessage);
				resMessage = userServiceRemote_sp.bindUser(reqMessage);
				logger.info("【绑定第三方网站用户接口bindUser】输出参数：" +resMessage);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("【绑定第三方网站用户接口bindUser】异常",e);
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433002);
			}
			if(!RetCode.SUCCESS.equals(resMessage.getRetCode())){
				logger.info("【绑定第三方网站用户接口失败bindUser 】");
				return ResultJsonUtil.resultJson(RetCode.FAIL,MsgConsts.E00433125);
			}
		}
		
		Map<String, Object> result = weixinService.getUserGroup(openId);//获取对应的公众号菜单标签
		logger.info("此微信openId="+openId+"的原标签是="+result);
		if(RetCode.SUCCESS.equals(result.get(CommonConsts.RETCODE))){
			if(StringUtil.isNotEmpty(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
				if(!groupId.equals(StringUtil.trim(result.get(CommonConsts.GROUPID)))){
					Integer valueOf = Integer.valueOf(groupId);
					boolean group = weixinService.addUserGroup(openId,valueOf);//重新标记公众号菜单标签
					logger.info("此微信openId="+openId+"重新打"+groupId+"标签flag="+group);
				}
			}
		}else{
			Integer valueOf = Integer.valueOf(groupId);
			boolean group = weixinService.addUserGroup(openId,valueOf);
			logger.info("此微信openId="+openId+"重新打"+groupId+"标签flag="+group);
		}
		return ResultJsonUtil.resultJson(RetCode.SUCCESS,CommonConsts.SPACE);
	}

}
